package org.example.service;

import com.alipay.remoting.exception.CodecException;
import io.vertx.core.Vertx;
import io.vertx.core.datagram.DatagramSocket;
import io.vertx.core.datagram.DatagramSocketOptions;
import lombok.extern.slf4j.Slf4j;
import org.example.engine.MatchEngine;
import org.example.order.CmdPack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
@Slf4j
public class SeqServer {

    @Value("${server.engine.ip}")
    public String ip;
    @Value("${server.engine.port}")
    public int port;

    @Autowired
    CmdPackService cmdPackService;

    @PostConstruct
    public void init() {
        Vertx vertx = Vertx.vertx();
        DatagramSocket socket = vertx.createDatagramSocket(new DatagramSocketOptions());
        socket.handler(packet -> {
                    try {
                        CmdPack cmdPack = CmdPack.deserialize(packet.data().getBytes());
                        cmdPackService.addCmdPack(cmdPack);
                        log.info("收到排队机的请求。。{}",cmdPack);
                    } catch (CodecException e) {
                        log.error("反序列化cmdPack失败",e);
                    }
                }).listen(port,ip)
                .onComplete(asyncResult -> {
                    System.out.println(asyncResult.succeeded());
                }).onFailure((err) -> {
                    System.out.println("监听失败:"+port);
                });
    }
}
